package chenshuaiwen.service.collection;

import chenshuaiwen.domain.dto.BaseDto;
import chenshuaiwen.domain.entity.BaseEntity;
import chenshuaiwen.domain.vo.BaseVo;
import chenshuaiwen.domain.vo.Result;
import chenshuaiwen.service.IBaseService;

import java.util.*;

/**
 * 业务层基类-基于容器存储数据
 *
 * @author 陈帅闻
 * @since 2025/5/26 11:12
 */
@Deprecated
abstract class BaseService<
        Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo extends BaseVo> implements IBaseService<Entity,Dto>{

    Map<Integer, Entity> data = new HashMap<>();

    Vo[] temp;

    private int idCounter = 1;

    @Override
    public boolean existsById(int id) {
        return data.containsKey(id);
    }

    @Override
    public Entity findById(int id) {
        return data.get(id);
    }

    abstract Vo convertToVo(Entity entity);

    @Override
    public Result list() {
//        List<Vo> list = new ArrayList<>();
//        Collection<Entity> values = data.values();
//        for(Entity entity : values){
//            list.add(convertToVo(entity));
//        }
        List<Vo> list = data.values().stream().map(this::convertToVo).toList();
        return Result.success("查询成功", list.toArray(temp));
    }

    abstract Entity createEntity(Dto dto, int id);

    @Override
    public Result create(Dto dto) {
        Entity entity = createEntity(dto, idCounter++);
        data.put(entity.getId(), entity);
        return Result.success("创建成功", null);
    }

    abstract void updateEntity(Dto dto,Entity entity);
    @Override
    public Result update(Dto dto, int id) {
        if(!existsById(id)){
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity = data.get(id);
        updateEntity(dto, entity);
        return Result.success("更新成功", null);
    }
}
